package com.example.wallet.db

import com.example.shushiyunsst.fragment.main.constant.CURRENT_ACCOUNT_KEY
import com.example.wallet.bean.AccountInfo
import com.example.wallet.createAccount
import com.example.wallet.utils.Preference

class AccountInfoManager private constructor() {

    companion object {

        val INSTANCE: AccountInfoManager by lazy {
            AccountInfoManager()
        }
    }

    private lateinit var mAccountInfo: AccountInfo

    private var mAccountInfoInit = false

    fun getAccountInfo(): AccountInfo {

        if (mAccountInfoInit) return mAccountInfo

        val accountInfoDao = AccountDatabase.getInstance().getAccountInfoDao()

        val currentAccount = Preference.HOLDER.getCustomAppProfile(CURRENT_ACCOUNT_KEY)

        if (currentAccount.isNullOrEmpty()) {
            mAccountInfo = createAccount()
            accountInfoDao.save(mAccountInfo)
            Preference.HOLDER.addCustomAppProfile(CURRENT_ACCOUNT_KEY, mAccountInfo.address)
        } else {
            val cache = accountInfoDao.getCache(currentAccount)
            if (cache != null) {
                mAccountInfo = cache
            } else {
                mAccountInfoInit = false
            }
        }
        mAccountInfoInit = true

        return mAccountInfo
    }
}